﻿//------------------------------------------------------------------------------
// <copyright file="Configuration.cs" company="Robert MacLean">
//      Copyright © Robert MacLean.  All Rights Reserved.
// </copyright>
//
//  This code released under the terms of the 
//  Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//------------------------------------------------------------------------------

namespace FindResultsTweak
{
    using System;
    using System.Drawing;
    using System.Globalization;
    using System.Windows.Forms;
    using Microsoft.Win32;

    /// <summary>
    /// 
    /// </summary>
    public partial class ConfigurationForm : Form
    {
        private ContextMenuStrip slugMenuStrip;
        private Slugs slugs = new Slugs();
        private const string defaultFormat = "$p($l):$T\\n";
        private Samples samples = new Samples();
        private Point lastCursorPosition;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationForm"/> class.
        /// </summary>
        public ConfigurationForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Click event of the OKButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void OKButton_Click(object sender, EventArgs e)
        {
            RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VisualStudio\10.0\Find", true);
            try
            {
                switch (UseDefaultCheckBox.CheckState)
                {
                    case CheckState.Unchecked:
                        {
                            registryKey.SetValue("Find result format", FormatStringTextBox.Text);
                            break;
                        }
                    case CheckState.Checked:
                        {
                            if (registryKey.GetValue("Find result format") != null)
                            {
                                registryKey.DeleteValue("Find result format");
                            }
                            break;
                        }
                }
            }
            finally
            {
                registryKey.Close();
            }
        }

        /// <summary>
        /// Inserts the data tag.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void InsertDataTag(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            int charIndex = FormatStringTextBox.GetCharIndexFromPosition(lastCursorPosition);
            FormatStringTextBox.Text += (string)menuItem.Tag;
            FormatStringTextBox.Focus();
        }

        /// <summary>
        /// Handles the Click event of the InsertButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void InsertButton_Click(object sender, EventArgs e)
        {
            if (slugMenuStrip == null)
            {
                slugMenuStrip = new ContextMenuStrip();
                foreach (var group in slugs.GroupedSlugs)
                {
                    ToolStripMenuItem baseMenuItem = new ToolStripMenuItem(group.Key);
                    foreach (var slug in group)
                    {
                        ToolStripMenuItem slugMenuitem = new ToolStripMenuItem(string.Format(CultureInfo.CurrentCulture, "{0} ({1})", slug.Description, slug.Tag));
                        slugMenuitem.Click += new EventHandler(InsertDataTag);
                        slugMenuitem.Tag = slug.Tag;
                        baseMenuItem.DropDownItems.Add(slugMenuitem);
                    }

                    slugMenuStrip.Items.Add(baseMenuItem);
                }
            }

            slugMenuStrip.Show(MousePosition);
        }

        /// <summary>
        /// Handles the Shown event of the ConfigurationForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ConfigurationForm_Shown(object sender, EventArgs e)
        {
            try
            {
                FormatStringTextBox.AutoCompleteCustomSource.AddRange(slugs.AutoCompleteSource);
                RegistryKey findResultsRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VisualStudio\10.0\FontAndColors\{5C48B2CB-0366-4FBF-9786-0BB37E945687}");
                if (findResultsRegistryKey != null)
                {
                    try
                    {
                        string fontName = (string)findResultsRegistryKey.GetValue("FontName", "Consolas");
                        float fontSize = (int)findResultsRegistryKey.GetValue("FontPointSize", 9);
                        int backgroundColorValue = (int)findResultsRegistryKey.GetValue("Plain Text Background", 16777215);
                        int foregroundColorValue = (int)findResultsRegistryKey.GetValue("Plain Text Foreground", 0);
                        if (backgroundColorValue == 33554432)
                        {
                            backgroundColorValue = 16777215; // white
                        }
                        if (foregroundColorValue == 33554432)
                        {
                            foregroundColorValue = 0; // black
                        }

                        Color backgroundColour = Color.FromArgb(backgroundColorValue);
                        Color foregroundColour = Color.FromArgb(foregroundColorValue);
                        FindResultsTextBox.Font = new Font(fontName, fontSize);
                        FindResultsTextBox.BackColor = Color.FromArgb(backgroundColour.B, backgroundColour.G, backgroundColour.R);
                        FindResultsTextBox.ForeColor = Color.FromArgb(foregroundColour.B, foregroundColour.G, foregroundColour.R);
                    }
                    finally
                    {
                        findResultsRegistryKey.Close();
                    }
                }

                RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VisualStudio\10.0\Find");
                try
                {
                    string formatterKey = registryKey.GetValue("Find result format") as string;
                    if (string.IsNullOrEmpty(formatterKey))
                    {
                        UseDefaultCheckBox.CheckState = CheckState.Checked;
                    }
                    else
                    {
                        UseDefaultCheckBox.CheckState = CheckState.Unchecked;
                        FormatStringTextBox.Text = formatterKey;
                    }
                }
                finally
                {
                    registryKey.Close();
                }

                UpdateExample();
            }
            catch (Exception err)
            {
                MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Sorry, an error has occurred. Message: {0}{1}{2}", err.Message, Environment.NewLine, err.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the FormatStringTextBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FormatStringTextBox_TextChanged(object sender, EventArgs e)
        {
            UpdateExample();
        }

        /// <summary>
        /// Updates the example.
        /// </summary>
        private void UpdateExample()
        {
            string formatString = defaultFormat;
            if (UseDefaultCheckBox.CheckState == CheckState.Unchecked)
            {
                formatString = FormatStringTextBox.Text;
            }

            string result = "Find all \"backgroundColor\", Subfolders, Find Results 1, \"Current Project\", \"*.*\"" + Environment.NewLine;
            foreach (Sample sample in samples.AllSamples)
            {
                result += "  " + sample.ToString(formatString);
            }
            result += "  Matching lines: 4    Matching files: 3    Total files searched: 13";

            FindResultsTextBox.Text = result;

        }

        /// <summary>
        /// Handles the CheckStateChanged event of the UseDefaultCheckBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void UseDefaultCheckBox_CheckStateChanged(object sender, EventArgs e)
        {
            if (UseDefaultCheckBox.CheckState == CheckState.Unchecked)
            {
                FormatStringTextBox.Enabled = true;
                if (string.IsNullOrEmpty(FormatStringTextBox.Text))
                {
                    FormatStringTextBox.Text = defaultFormat;
                }
            }
            else
            {
                FormatStringTextBox.Enabled = false;
            }

            UpdateExample();
        }

        /// <summary>
        /// Handles the Leave event of the FormatStringTextBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FormatStringTextBox_Leave(object sender, EventArgs e)
        {
            lastCursorPosition = FormatStringTextBox.Cursor.HotSpot;
        }

        /// <summary>
        /// Handles the Click event of the WebSiteButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void WebSiteButton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://findresultstweak.codeplex.com/");
        }

        /// <summary>
        /// Handles the Click event of the ThanksButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ThanksButton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://blogs.msdn.com/saraford/archive/2008/11/24/did-you-know-you-can-customize-how-search-results-are-displayed-in-the-find-results-window-363.aspx");
        }

        /// <summary>
        /// Handles the Click event of the AboutButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void AboutButton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.sadev.co.za/content/tweaking-find-results-window-visual-studio-2010");
        }
    }
}
